package vaani.internal.actionmanagers;

import java.util.LinkedList;
import java.util.List;
import vaani.internal.DBusCommand;
import vaani.internal.ProcessInstance;
import vaani.internal.ProcessInstanceDBus;
import vaani.internal.purple.Buddy;
import vaani.internal.purple.BuddyLocator;
import vaani.internal.purple.InstantMessageAccount;
import vaani.internal.purple.PidginHandler;
import vaani.internal.purple.Result;


/**
 *
 * @author sourcemorph
 */
public class InstantMessageManager extends GenericManagerDBusType {

    private List<Result> searchResult;

    public InstantMessageManager(List<String> arguments) {
        searchResult = new BuddyLocator(arguments).getResults();
        instances = new LinkedList<ProcessInstance>();
        System.out.println("no. of args = " + arguments.size());
        if(searchResult != null) {
            for(Result r : searchResult) {
                System.out.println(r.getBuddy().getName());
                instances.add(createProcessInstances(r));
            }
        }
    }
    
    @Override
    public boolean runProcess(int x) {
        ProcessInstanceDBus toExecute = (ProcessInstanceDBus) instances.get(x);
        switch(toExecute.getCommand().getMethod()) {
            case 1:     PidginHandler handler = new PidginHandler();
                        handler.makeConnection();
                        handler.startNewConversation((InstantMessageAccount) toExecute.getCommand().getArguments().get(0), (Buddy) toExecute.getCommand().getArguments().get(1));
                        handler.closeConnection();
                        break;
            default:    return false;
        }
        return true;
    }

    public ProcessInstanceDBus createProcessInstances(Result result) {
        String description = "Open a chat with ";
        if(result.getBuddy().getAlias() == null)
            description += result.getBuddy().getName();
        else
            description += result.getBuddy().getAlias();
        description += " on protocol " + result.getAccount().getProtocol();
        List<Object> arguments = new LinkedList<Object>();
        arguments.add(result.getAccount());
        arguments.add(result.getBuddy());
        return new ProcessInstanceDBus(description, new DBusCommand(1, arguments));
    }
}